import {Button, Form, InputNumber, message, Modal, Space, Switch} from "antd";
import React, {useEffect, useState} from "react";
import {useModel} from "@@/exports";
import CustomSelect from "@/pages/components/CustomSelect";
import {ActionType} from "@ant-design/pro-components";
import {
  addProductYieldOffsetUsingPOST,
  editProductYieldOffsetUsingPUT
} from "@/services/model/productYieldOffsetController";
import {
  getProductSeriesByProductCodeUsingGET,
  listProductByProductSeriesCodeUsingGET,
  listProductSeriesUsingGET,
  listProductUsingGET
} from "@/services/model/basePedigreeController";

type ModelProps = {
  saveType: string,
  isModalOpen: boolean,
  onCancel: () => void,
  initProductSeriesCode: string,
  initProductCode: string,
  editRecord: API.ProductYieldOffsetDTO,
  actionRef: React.MutableRefObject<ActionType | undefined>,
}

const layoutStyle = {
  labelCol: {span: 6},
  wrapperCol: {span: 16},
};
const tailLayout = {
  wrapperCol: {offset: 8, span: 16},
};

const AddOrEditModel: React.FC<ModelProps> = ({
                                                saveType,
                                                isModalOpen,
                                                onCancel,
                                                initProductSeriesCode,
                                                initProductCode,
                                                editRecord,
                                                actionRef
                                              }) => {
  const [selectProductSeriesValue, setSelectProductSeriesValue] = useState('');
  const [selectProductValue, setSelectProductValue] = useState('');
  const [editSwitch, setEditSwitch] = useState(false);
  const [addAndEditForm] = Form.useForm();


  // useEffect(() => {
  //   setSelectProductSeriesValue(initProductSeriesCode);
  //   setSelectProductValue(initProductCode);
  //   addAndEditForm.setFieldsValue(editRecord);
  //   setEditSwitch(editRecord.offset === 1)
  // }, [initProductSeriesCode, initProductCode, isModalOpen])
  // 替换为 --->
  const [prevItems, setPrevItems] = useState(isModalOpen);
  if (isModalOpen !== prevItems) {
    setPrevItems(isModalOpen);
    setSelectProductSeriesValue(initProductSeriesCode);
    setSelectProductValue(initProductCode);
    addAndEditForm.resetFields();
    addAndEditForm.setFieldsValue(editRecord);
    setEditSwitch(editRecord.offset === 1)
  }
  const {initialState} = useModel('@@initialState');

  const [productSeriesList, setProductSeriesList] = useState<{
    id: string | undefined,
    name: string | undefined
  }[]>([]);
  const [productList, setProductList] = useState<{
    id: string | undefined,
    name: string | undefined
  }[]>([]);
  useEffect(() => {
    listProductSeriesUsingGET().then((result) => {
      if (result.code === 0 && result.data) {
        const dataCodeList = result.data.filter((item: any) => item.code).map((item: any) => {
          return {
            id: item.code,
            name: item.name + " [" + item.code + "]"
          }
        })
        setProductSeriesList(dataCodeList);
      }
    });
    listProductUsingGET().then((result) => {
      if (result.code === 0 && result.data) {
        const dataList = result.data.filter((item: any) => item).map((item: any) => {
          return {
            id: item.code,
            name: item.code,
          }
        })
        setProductList(dataList);
      }
    });
  }, []);
  useEffect(() => {
    // 筛选出当前产品系列下所有产品编码
    listProductByProductSeriesCodeUsingGET({
      productSeriesCode: selectProductSeriesValue,
    }).then((result) => {
      if (result.code === 0 && result.data) {
        const dataList = result.data.filter((item: any) => item).map((item: any) => {
          return {
            id: item.code,
            name: item.code,
          }
        })
        setProductList(dataList);
      }
    });
  }, [selectProductSeriesValue])
  const checkOffsetFail = (value: any) => {
    if (value.maxOffsetYield + value.offsetThreshold > 100) {
      message.warning("阈值补偿和最大良率补偿相加不能大于100%");
      return true;
    }
    if (value.maxOffsetYield < value.minOffsetYield) {
      message.warning("最小offset值不能大于最大offset值");
      return true;
    }
    return false;
  }
  const onSave = async (value: any) => {
    if (checkOffsetFail(value)) {
      return;
    }
    const randomOffsetYield = Math.floor(Math.random() * (value.maxOffsetYield - value.minOffsetYield + 1)) + value.minOffsetYield;
    const newAttendanceInfo: API.AddProductYieldOffsetQuery = {
      currentUserId: initialState?.currentUser?.id,
      /** 补偿后良率 */
      // finalYield: value.offsetYield * 0.01 + value.offsetThreshold * 0.01,
      finalYield: Number(((randomOffsetYield + value.offsetThreshold) * 0.01).toFixed(3)),
      /** 是否开启补偿 */
      offset: value.offset ? 1 : 0,
      /** offset值 */
      minOffsetYield: Number((value.minOffsetYield * 0.01).toFixed(3)),
      maxOffsetYield: Number((value.maxOffsetYield * 0.01).toFixed(3)),
      /** 产品代码 */
      productSeriesCode: selectProductSeriesValue,
      /** 产品系列代码 */
      productCode: selectProductValue,
      /** 阈值补偿 */
      offsetThreshold: Number((value.offsetThreshold * 0.01).toFixed(3)),
    };
    console.log(newAttendanceInfo);
    const result = await addProductYieldOffsetUsingPOST(newAttendanceInfo);
    if (result.code === 0 && result.data) {
      message.success('添加成功');
      onCancel();
    } else {
      message.warning(result.message);
    }
    actionRef.current?.reload();
  };
  const onEdit = async (value: any) => {
    if (checkOffsetFail(value)) {
      return;
    }
    const randomOffsetYield = Math.floor(Math.random() * (value.maxOffsetYield - value.minOffsetYield + 1)) + value.minOffsetYield;
    const newAttendanceInfo: API.EditProductYieldOffsetQuery = {
      id: value.id,
      currentUserId: initialState?.currentUser?.id,
      /** 补偿后良率 */
      finalYield: Number((randomOffsetYield * 0.01 + value.offsetThreshold * 0.01).toFixed(3)),
      /** 是否开启补偿 */
      offset: value.offset ? 1 : 0,
      /** offset值 */
      minOffsetYield: Number((value.minOffsetYield * 0.01).toFixed(3)),
      maxOffsetYield: Number((value.maxOffsetYield * 0.01).toFixed(3)),
      /** 产品代码 */
      productSeriesCode: selectProductSeriesValue,
      /** 产品系列代码 */
      productCode: selectProductValue,
      /** 阈值补偿 */
      offsetThreshold: Number((value.offsetThreshold * 0.01).toFixed(3)),
    };
    const result = await editProductYieldOffsetUsingPUT(newAttendanceInfo);

    if (result.code === 0 && result.data) {
      message.success('修改成功');
      onCancel();
    } else {
      message.warning(result.message);
    }
    actionRef.current?.reload();
  };
  const onReset = () => {
    setSelectProductSeriesValue('');
    setSelectProductValue('')
    setEditSwitch(false);
    addAndEditForm.resetFields();
  };

  return (
    <>
      <Modal title={saveType === 'edit' ? '修改产线工序' : '新增产线工序'} open={isModalOpen}
             onCancel={onCancel}
             footer={false}>
        <Form
          name="basic"
          form={addAndEditForm}
          {...layoutStyle}
          style={{maxWidth: 500}}
          onFinish={saveType === 'edit' ? onEdit : onSave}
        >
          <Form.Item
            label="id"
            key='id'
            name='id'
            hidden={true}
          >
          </Form.Item>
          <Form.Item
            label="产品系列"
            key='productSeriesCode'
            name='productSeriesCode'
          >
            <CustomSelect name={''} selectDate={selectProductSeriesValue} datalist={productSeriesList} setSelectData={(value) => {
              setSelectProductSeriesValue(value);
              setSelectProductValue('')
            }}/>
          </Form.Item>
          <Form.Item
            label="产品代码"
            key='productCode'
            name='productCode'
          >
            <CustomSelect name={''} selectDate={selectProductValue} datalist={productList} setSelectData={(value) => {
              setSelectProductValue(value);
              getProductSeriesByProductCodeUsingGET({
                productCode: value,
              }).then((result) => {
                if (result.code === 0 && result.data && result.data.code) {
                  setSelectProductSeriesValue(result.data.code)
                }
              });
            }}/>
          </Form.Item>
          <Form.Item
            label="阈值补偿"
            key='offsetThreshold'
            name='offsetThreshold'
          >
            <InputNumber
              formatter={(value) => `${value}%`}
              parser={(value) => value!.replace('%', '')}
            />
          </Form.Item>
          <Form.Item label="是否开启补偿" key='offset' name='offset' valuePropName="value">
            <Switch checked={editSwitch} onChange={(value) => setEditSwitch(value)}/>
          </Form.Item>
          <Form.Item
            label="最小OFFSET值"
          >
            <Form.Item
              style={{display: 'inline-flex', width: 'calc(40% - 4px)'}}
              key='minOffsetYield'
              name='minOffsetYield'
            >
              <InputNumber
                formatter={(value) => `${value}%`}
                parser={(value) => value!.replace('%', '')}
              />
            </Form.Item>
            <Form.Item
              label="最大OFFSET值"
              style={{display: 'inline-flex', width: 'calc(50% - 4px)', marginLeft: '8px'}}
              key='maxOffsetYield'
              name='maxOffsetYield'
            >
              <InputNumber
                formatter={(value) => `${value}%`}
                parser={(value) => value!.replace('%', '')}
              />
            </Form.Item>
          </Form.Item>


          <Form.Item {...tailLayout} key="submit&reset">
            <Space>
              <Button type="primary" htmlType="submit" key="submit">
                提交
              </Button>
              <Button disabled={saveType === 'edit'} htmlType="button" onClick={onReset} key="reset">
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default AddOrEditModel;



